from flask import Blueprint, jsonify, abort
from core import db
from core import model
import requests
from core.producer import publish
api = Blueprint('api', __name__)


@api.route('/products')
def index():  # 获取所有图片
    product_list = db.session.query(model.Product).all()
    return jsonify(product_list)


@api.route('/products/like/<int:id>', methods=['POST'])
def like(id):
    req = requests.get('http://127.0.0.1:8000/user')
    json = req.json()
    try:
        user_like = model.UserLike(user_id=json['id'], product_id=id)
        db.session.add(user_like)
        db.session.commit()

        publish('product_liked', id)
    except:
        # abort(400, 'You already liked this product')
        return jsonify({
            'code': '101',
            'msg': '您已经收藏过'
        })
    return jsonify({
        'code': '100',
        'msg': '收藏成功'
    })
